import fs from 'fs';
import querystring from 'querystring'

function register(req,res){
        let buf=Buffer.alloc(0)
        req.on('data',chunk=>{
            buf=Buffer.concat([buf,chunk])
        })
        req.on('end',()=>{
            let users =querystring.parse(buf.toString());
            // let defaultData = fs.writeFileSync('./data/user.json',users,'utf-8')
            if(fs.existsSync('./data/user.json',users,'utf-8')){

                let userlist=fs.readFileSync('./data/user.json','utf-8');

                if(userlist.length===0){
                    userlist=[];
                    userlist.push(users)
                    fs.writeFileSync('./data/user.json',JSON.stringify(userlist),'utf-8')

                    //解决乱码的功能
                    res.writeHead(200,'ok',{'Content-Type':'application/json;charset=utf-8'})

                    res.end('恭喜你成为我们第一个用户')
                }else{
                    userlist=JSON.parse(userlist);
                    let msg =userlist.some(item=>{
                        return item.user===users.user;
                    })
                    if(msg){
                        res.writeHead(200,'ok',{'Content-Type':'application/json;charset=utf-8'})
                        res.end('用户名已存在，请重新注册')
                    }else{
                        userlist.push(users)
                        fs.writeFileSync('./data/user.json',JSON.stringify(userlist),'utf-8')
                        res.writeHead(200,'ok',{'Content-Type':'application/json;charset=utf-8'})
                        res.end('恭喜你注册成功')
                    }
                }
            }
        })
}
export default register;